package FenxiaoService

import (
	"context"
	"errors"
	"gdshop-admin-go-api/app/entity"
	"gdshop-admin-go-api/app/response/FenxiaoResp"
	toolsDb "gdshop-admin-go-api/library/tools/db"
	"gdshop-admin-go-api/library/tools/myCache"
	"gdshop-admin-go-api/library/tools/mylog"
	"github.com/gogf/gf/errors/gerror"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/util/gconv"
	"time"
)

// 当前文件前后端API通用

func GetFenxiaoUserListByCache(ctx context.Context) ([]*entity.FenxiaoUser, error) {
	var fuList []*entity.FenxiaoUser
	all, err := myCache.GetOrSetFunc("table:fenxiao_user_all", func() (interface{}, error) {
		all, err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "fenxiao_user").All()
		if err != nil {
			return nil, err
		}
		return all, nil
	}, 600*time.Second)
	if err != nil {
		return nil, err
	}
	err = gconv.Scan(all, &fuList)
	if err != nil {
		return nil, err
	}
	if fuList == nil {
		return nil, errors.New("没有数据")
	}

	return fuList, nil
}

func GetFenxiaoUserModelByMemberId(ctx context.Context, memberId int) (*entity.FenxiaoUser, error) {
	var fuList []*entity.FenxiaoUser
	all, err := myCache.GetOrSetFunc("table:fenxiao_user_all", func() (interface{}, error) {
		all, err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "fenxiao_user").All()
		if err != nil {
			return nil, err
		}
		return all, nil
	}, 600*time.Second)
	if err != nil {
		return nil, err
	}
	err = gconv.Scan(all, &fuList)
	if err != nil {
		return nil, err
	}
	if fuList == nil {
		return nil, gerror.NewCode(6000, "fenxiao_user 没有数据")
	}

	for _, item := range fuList {
		if item.MemberId == memberId {
			return item, nil
		}
	}
	return nil, gerror.NewCode(6000, "fenxiao_user 没有找到数据")
}

func GetFenxiaoUserModelByFenxiaoUserId(ctx context.Context, fenxiaoUserId int) (*entity.FenxiaoUser, error) {
	fuList, err := GetFenxiaoUserListByCache(ctx)
	if err != nil {
		return nil, err
	}

	for _, item := range fuList {
		if item.Id == fenxiaoUserId {
			return item, nil
		}
	}
	return nil, errors.New("没有找到数据")
}

// GetMemberRate 获取会员佣金比例
func GetMemberRate(ctx context.Context, memberId, level int) float64 {
	if memberId < 1 {
		return 0
	}
	// TODO 需要判断配置，是否开启分销
	if !ConfigLevelConfig() {
		return 0
	}

	fuModel, err := GetFenxiaoUserModelByMemberId(ctx, memberId)
	if err != nil {
		mylog.ErrorLog("GetMemberRate fenxiao_user " + err.Error())
		return 0
	}

	if fuModel == nil {
		mylog.ErrorLog("GetMemberRate fenxiao_user 找不到数据")
		return 0
	}

	if fuModel.Status == 0 {
		return 0
	}
	var flModel *entity.FenxiaoLevel
	err = toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "fenxiao_level").Cache(600*time.Second).Where("id", fuModel.LevelId).Scan(&flModel)
	if err != nil {
		mylog.ErrorLog("GetMemberRate fenxiao_level " + err.Error())
		return 0
	}

	if flModel == nil {
		mylog.ErrorLog("GetMemberRate fenxiao_level 找不到数据")
		return 0
	}

	switch level {
	case 1:
		return float64(flModel.OneRate) / 100000.00
	case 2:
		return float64(flModel.TwoRate) / 100000.00
	case 3:
		return float64(flModel.ThreeRate) / 100000.00
	default:
		return 0
	}
}

func GetMemberRateByFenxiaoUserId(ctx context.Context, fenxiaoUserId, level int) float64 {
	if fenxiaoUserId < 1 {
		return 0
	}
	// TODO 需要判断配置，是否开启分销
	if !ConfigLevelConfig() {
		return 0
	}

	fuModel, err := GetFenxiaoUserModelByFenxiaoUserId(ctx, fenxiaoUserId)
	if err != nil {
		mylog.ErrorLog("GetMemberRate fenxiao_user " + err.Error())
		return 0
	}

	if fuModel == nil {
		mylog.ErrorLog("GetMemberRate fenxiao_user 找不到数据")
		return 0
	}

	if fuModel.Status == 0 {
		return 0
	}
	var flModel *entity.FenxiaoLevel
	err = toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "fenxiao_level").Cache(600*time.Second).Where("id", fuModel.LevelId).Scan(&flModel)
	if err != nil {
		mylog.ErrorLog("GetMemberRate fenxiao_level " + err.Error())
		return 0
	}

	if flModel == nil {
		mylog.ErrorLog("GetMemberRate fenxiao_level 找不到数据")
		return 0
	}

	switch level {
	case 1:
		return float64(flModel.OneRate) / 100000.00
	case 2:
		return float64(flModel.TwoRate) / 100000.00
	case 3:
		return float64(flModel.ThreeRate) / 100000.00
	default:
		return 0
	}
}

// GetMemberGoodsBrokerage 获取指定会员商品返佣
func GetMemberGoodsBrokerage(ctx context.Context, memberId, goodsId int) float64 {
	rate := GetMemberRate(ctx, memberId, 1)
	if rate < 0.000001 {
		return 0
	}
	var fgModel *entity.FenxiaoGoods
	err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "fenxiao_goods").Where("goods_id", goodsId).Scan(&fgModel)
	if err != nil {
		mylog.ErrorLog("GetMemberGoodsBrokerage fenxiao_goods " + err.Error())
		return 0
	}

	if fgModel == nil {
		mylog.ErrorLog("GetMemberGoodsBrokerage fenxiao_goods 找不到数据")
		return 0
	}

	// 是否启用
	if fgModel.Status == 0 {
		// 禁用，直接返回0
		return 0
	}

	// 取出规格最高价钱
	maxPrice, err := toolsDb.GetUnSafaTable(ctx, "goods_option").As("go").LeftJoin("goods g", "go.goods_id = g.id").Where(
		"g.delete_at<1 AND go.delete_at<1 AND go.is_open = 1 AND go.goods_id = ?", goodsId).Max("go.sell_price")
	if err != nil {
		mylog.ErrorLog("GetMemberGoodsBrokerage goods_option " + err.Error())
		return 0
	}

	return rate * maxPrice
}

func GetUserInfo(ctx context.Context, memberId, level int) *FenxiaoResp.UserInfo {
	fuModel, err := GetFenxiaoUserModelByMemberId(ctx, memberId)
	if err != nil {
		return nil
	}
	if fuModel == nil {
		return nil
	}
	return &FenxiaoResp.UserInfo{
		Rate:          GetMemberRate(ctx, memberId, level),
		LevelId:       fuModel.LevelId,
		FenxiaoUserId: fuModel.Id,
		MemberId:      memberId,
		Status:        fuModel.Status,
	}
}

// GetUserInfoAndGoodsRateByFenxiaoUserId
// level = 1 时 应该是自购的
func GetUserInfoAndGoodsRateByFenxiaoUserId(ctx context.Context, fenxiaoUserId, level, goodsId int) *FenxiaoResp.UserInfo {
	fuModel, err := GetFenxiaoUserModelByFenxiaoUserId(ctx, fenxiaoUserId)
	if err != nil {
		return nil
	}
	if fuModel == nil {
		return nil
	}
	var rate float64
	fglModel, err := GetGoodsLevel(ctx, goodsId, fuModel.LevelId)
	if err != nil {
		return nil
	}
	switch level {
	case 3:
		rate = float64(fglModel.ThreeRate) / 100000.00
		break
	case 2:
		rate = float64(fglModel.TwoRate) / 100000.00
		break
	case 1:
		rate = float64(fglModel.OneRate) / 100000.00
		break
	default:
		rate = float64(fglModel.OneRate) / 100000.00
		break
	}
	return &FenxiaoResp.UserInfo{
		Rate:          rate,
		LevelId:       fuModel.LevelId,
		FenxiaoUserId: fenxiaoUserId,
		MemberId:      fuModel.MemberId,
		Status:        fuModel.Status,
	}
}

// GetGoodsLevel 获取指定商品的分销设置数据
func GetGoodsLevel(ctx context.Context, goodsId, levelId int) (*entity.FenxiaoGoodsLevel, error) {
	var fglModel *entity.FenxiaoGoodsLevel
	err := toolsDb.GetUnSafaTable(ctx, "fenxiao_goods").As("fg").
		LeftJoin("fenxiao_goods_level fgl", "fgl.fenxiao_goods_id = fg.id").Fields("fgl.*").
		Where(g.Map{
			"fg.goods_id":  goodsId,
			"fg.status":    1,
			"fgl.level_id": levelId,
		}).Scan(&fglModel)

	if err != nil {
		return nil, err
	}

	return fglModel, nil
}

// 输入当前购买会员ID，获取 当前、上级、上上级 相关信息
func GetMemberRelationship(ctx context.Context, oneMemberId int) (*FenxiaoResp.GetMemberRelationship, error) {
	// 判断分销功能是否开放
	// 不开放直接返回
	if !ConfigLevelConfig() {
		return nil, gerror.NewCode(6000, "分销功能未开启")
	}
	fanhui := &FenxiaoResp.GetMemberRelationship{}
	fuModel, err := GetFenxiaoUserModelByMemberId(ctx, oneMemberId)
	if err != nil {
		return nil, gerror.NewCode(6001, err.Error())
	}

	if fuModel == nil {
		return nil, gerror.NewCode(6003, "找不到当前会员数据，当前会员未加入分销")
	}
	// 开启自购分佣
	if ConfigSelfPurchaseRebate() {
		fanhui.One = GetUserInfo(ctx, oneMemberId, 1)
	}
	// 上级
	if fuModel.ParentId > 0 {
		fanhui.Two = GetUserInfo(ctx, fuModel.ParentId, 2)
	}
	// 上上级
	if fuModel.ParentParentId > 0 {
		fanhui.Three = GetUserInfo(ctx, fuModel.ParentParentId, 3)
	}

	return fanhui, nil
}

func GetFenxiaoOrderLevelFields(levelNum int, profix string) []string {
	levelNameProfix := []string{}
	switch levelNum {
	case 1:
		levelNameProfix = []string{
			"one",
		}
		break
	case 2:
		levelNameProfix = []string{
			"one",
			"two",
		}
		break
	default:
		levelNameProfix = []string{
			"one",
			"two",
			"three",
		}
		break
	}
	fanhui := []string{}
	for _, item := range levelNameProfix {
		fanhui = append(fanhui, profix+item+"_rate")
		fanhui = append(fanhui, profix+item+"_level_id")
		fanhui = append(fanhui, profix+item+"_fenxiao_user_id")
		fanhui = append(fanhui, profix+item+"_member_id")
	}

	return fanhui
}
